package com.squid.base.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.squid.base.common.error.ExceptionFactory;
import com.squid.base.utils.file.FileDTO;
import com.squid.base.utils.file.FileTypeUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.List;

@Slf4j
public class ExcelUtils {
    /**
     * 导入excel文件,
     *
     * @param multipartFile         多部分文件
     * @param tClass                t类
     * @param analysisEventListener 分析事件监听器，在监听器里添加保存数据库，继承AnalysisEventListener
     */
    public static <T> void importExcelFile(MultipartFile multipartFile, Class<T> tClass, AnalysisEventListener<T> analysisEventListener) {
        FileDTO fileDTO = FileTypeUtils.returnFileDTO(multipartFile);
        importExcelFile(fileDTO, tClass, analysisEventListener);
    }

    public static <T> void importExcelFile(FileDTO fileDTO, Class<T> tClass, AnalysisEventListener<T> analysisEventListener) {
        String fileExtName = fileDTO.getFileExtName();
        if (ExcelTypeEnum.XLSX.getValue().split("\\.")[1].equals(fileExtName)) {
            EasyExcel.read(fileDTO.getFile(), tClass, analysisEventListener).excelType(ExcelTypeEnum.XLSX).sheet().doRead();
        }
        else if (ExcelTypeEnum.XLS.getValue().split("\\.")[1].equals(fileExtName)) {
            EasyExcel.read(fileDTO.getFile(), tClass, analysisEventListener).excelType(ExcelTypeEnum.XLS).sheet().doRead();
        }
        else if (ExcelTypeEnum.CSV.getValue().split("\\.")[1].equals(fileExtName)) {
            EasyExcel.read(fileDTO.getFile(), tClass, analysisEventListener).excelType(ExcelTypeEnum.CSV).sheet().doRead();
        }else{
            throw ExceptionFactory.instanceServerException(StrUtil.format("不支持的文件类型，{}",fileExtName));
        }
    }

    public static <T> void exportExcelFile(HttpServletResponse response, Class<T> tClass, List<T> data, String sheetName, String fileName) {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), tClass).autoCloseStream(Boolean.FALSE).sheet(sheetName)
                    .doWrite(data);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            throw ExceptionFactory.instanceServerException("excel导出失败", e);
        }
    }
}
